package org.dromara.manu.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.manu.domain.ManuKpiRecord;
import org.dromara.manu.mapper.ManuKpiRecordMapper;
import org.springframework.stereotype.Service;
import org.dromara.manu.domain.bo.ManuKpiMasterBo;
import org.dromara.manu.domain.vo.ManuKpiMasterVo;
import org.dromara.manu.domain.ManuKpiMaster;
import org.dromara.manu.mapper.ManuKpiMasterMapper;
import org.dromara.manu.service.IManuKpiMasterService;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import static org.dromara.common.core.utils.DateUtils.getDayListByYear;
import static org.dromara.common.core.utils.DateUtils.getSundayList;

/**
 * 主数据Service业务层处理
 *
 * @author Bin Liu
 * @date 2024-08-23
 */
@RequiredArgsConstructor
@Service
public class ManuKpiMasterServiceImpl implements IManuKpiMasterService {

    private final ManuKpiMasterMapper baseMapper;
    private final ManuKpiRecordMapper recordMapper;

    /**
     * 查询主数据
     *
     * @param id 主键
     * @return 主数据
     */
    @Override
    public ManuKpiMasterVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询主数据列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 主数据分页列表
     */
    @Override
    public TableDataInfo<ManuKpiMasterVo> queryPageList(ManuKpiMasterBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ManuKpiMaster> lqw = buildQueryWrapper(bo);
        Page<ManuKpiMasterVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的主数据列表
     *
     * @param bo 查询条件
     * @return 主数据列表
     */
    @Override
    public List<ManuKpiMasterVo> queryList(ManuKpiMasterBo bo) {
        LambdaQueryWrapper<ManuKpiMaster> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ManuKpiMaster> buildQueryWrapper(ManuKpiMasterBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ManuKpiMaster> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), ManuKpiMaster::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), ManuKpiMaster::getDescription, bo.getDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), ManuKpiMaster::getCategory, bo.getCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getDataCategory()), ManuKpiMaster::getDataCategory, bo.getDataCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getScope()), ManuKpiMaster::getScope, bo.getScope());
        return lqw;
    }

    private List<ManuKpiRecord> generateAnnualRecordByMasterYear(ManuKpiMaster master, Integer year){
        List<ManuKpiRecord> records = new ArrayList<ManuKpiRecord>();
        ManuKpiRecord iniRecord = new ManuKpiRecord();
        iniRecord.setMasterId(master.getId());
        iniRecord.setYearNum(year);
        if(master.getByAnnual()){
            records.add(iniRecord);
        }
        if(master.getByMonth()){
            for(int i = 1; i <= 12; i++){
                ManuKpiRecord record = new ManuKpiRecord();
                record.setMasterId(master.getId());
                record.setYearNum(year);
                record.setMonthNum(i);
                records.add(record);
            }
        }
        if(master.getByWeek()){
            List<Date> sundayList = getSundayList(year);
            for(int i = 1; i <= sundayList.size(); i++){
                ManuKpiRecord record = new ManuKpiRecord();
                record.setMasterId(master.getId());
                record.setYearNum(year);
                record.setWeekNum(i);
                records.add(record);
            }
        }
        if(master.getByDaily()){
            getDayListByYear(year).forEach(date -> {
                ManuKpiRecord record = new ManuKpiRecord();
                record.setYearNum(year);
                record.setMasterId(master.getId());
                record.setByDaily(date);
                records.add(record);
            });
        }
        if(master.getByShift()){
            getDayListByYear(year).forEach(date -> {
                for(int i = 1; i <= 2; i++){
                    ManuKpiRecord record = new ManuKpiRecord();
                    record.setMasterId(master.getId());
                    record.setYearNum(year);
                    record.setByDaily(date);
                    record.setByShift(i);
                    records.add(record);
                }
            });
        }
        return records;
    }

    /**
     * 新增主数据
     *
     * @param bo 主数据
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ManuKpiMasterBo bo) {
        ManuKpiMaster add = MapstructUtils.convert(bo, ManuKpiMaster.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改主数据
     *
     * @param bo 主数据
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ManuKpiMasterBo bo) {
        ManuKpiMaster update = MapstructUtils.convert(bo, ManuKpiMaster.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ManuKpiMaster entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除主数据信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int generateAllByYear(Integer year) {
        AtomicReference<Integer> recordNum = new AtomicReference<>(0);
        //使用baseMapper获取所有数据
        List<ManuKpiMaster> masterList = baseMapper.selectList(Wrappers.emptyWrapper());
        masterList.forEach( master-> {
            List<ManuKpiRecord> records = generateAnnualRecordByMasterYear(master, year);
            recordMapper.insertBatch(records);
            recordNum.set(records.size());
        });
        return recordNum.get();
    }
}
